package com.huike.contract.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.huike.business.domain.TbBusiness;
import com.huike.business.mapper.TbBusinessMapper;
import com.huike.clues.domain.SysUser;
import com.huike.clues.domain.TbAssignRecord;
import com.huike.clues.domain.TbClue;
import com.huike.clues.domain.TbRulePool;
import com.huike.clues.mapper.SysUserMapper;
import com.huike.clues.mapper.TbAssignRecordMapper;
import com.huike.clues.mapper.TbClueMapper;
import com.huike.clues.mapper.TbRulePoolMapper;
import com.huike.common.constant.ErrorMessageConstants;
import com.huike.common.core.domain.AjaxResult;
import com.huike.common.core.domain.entity.SysUserDTO;
import com.huike.common.core.page.TableDataInfo;
import com.huike.common.exception.BaseException;
import com.huike.contract.domain.dto.GetTransferListDTO;
import com.huike.contract.domain.vo.TransferVo;
import com.huike.contract.mapper.TransferMapper;
import com.huike.contract.service.TransferService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @Description TransferServiceImpl
 * @Author zhuzi
 * @Date 2023/10/17
 */
@RequiredArgsConstructor
@Service
@Slf4j
public class TransferServiceImpl extends ServiceImpl<TransferMapper, TbAssignRecord> implements TransferService {

    private final TransferMapper mapper;

    private final SysUserMapper sysUserMapper;

    private final TbAssignRecordMapper tbAssignRecordMapper;

    private final TbRulePoolMapper tbRulePoolMapper;

    private final TbClueMapper tbClueMapper;

    private final TbBusinessMapper tbBusinessMapper;

    /**
     * 获取转派列表
     *
     * @param dto 筛选条件
     */
    @Override
    public TableDataInfo<List<TransferVo>> getTransferList(GetTransferListDTO dto) {
        PageHelper.startPage(dto.getPageNum(), dto.getPageSize());
        Page<TransferVo> page = mapper.getTransferList(dto);
        TableDataInfo<List<TransferVo>> res = new TableDataInfo<>(page.getResult(), page.getTotal());
        res.setCode(200);
        res.setMsg("查询成功");
        return res;
    }

    /**
     * 处理转派
     *
     * @param type           转派类型：0-线索，1-商机
     * @param userId         从哪个用户转派出去
     * @param transferUserId 转派给哪个用户
     * @return flag-转派处理结果是否成功，msg-失败消息
     */
    @Override
    @Transactional
    public Map<String, Object> transfer(Integer type, Long userId, Long transferUserId) {
        Map<String, Object> map = new HashMap<>();
        // 判断用户合法性
        SysUser user = sysUserMapper.selectById(transferUserId);
        if (user == null || user.getStatus().equals("1")) {
            throw new BaseException(ErrorMessageConstants.USER_DOES_NOT_EXIST);
        }
        // 线索与商机业务区分
        switch (type) {
            case 0: // 线索
                // 获取用户还能持有的线索数
                LambdaQueryWrapper<TbAssignRecord> queryWrapper1 = new LambdaQueryWrapper<>();
                queryWrapper1.eq(TbAssignRecord::getType, type).eq(TbAssignRecord::getLatest, 1).eq(TbAssignRecord::getUserId, transferUserId);
                Integer clueCount = tbAssignRecordMapper.selectCount(queryWrapper1);
                LambdaQueryWrapper<TbRulePool> queryWrapper2 = new LambdaQueryWrapper<>();
                queryWrapper2.select(TbRulePool::getMaxNunmber);
                queryWrapper2.eq(TbRulePool::getType, type);
                Integer clueMax = tbRulePoolMapper.selectOne(queryWrapper2).getMaxNunmber();
                if (clueCount >= clueMax) {
                    throw new BaseException(ErrorMessageConstants.HOLDING_TOO_MANY_CLUE);
                }
                // 获取要转派的线索
                List<TbClue> clueList = tbClueMapper.getTransferClueListByUserId(userId);
                // 逐一转派
                for (int i = 0; i < clueList.size(); i++) {
                    if (clueCount++ >= clueMax) {
                        map.put("flag", false);
                        map.put("msg", "成功分配" + i + "个线索，剩余" + (clueList.size() - i) + "个线索分配失败");
                        return map;
                    }
                    TbClue clue = clueList.get(i);
                    tbAssignRecordMapper.updateTbAssignRecordByAssignId(clue.getId());
                    if (!save(TbAssignRecord.builder()
                            .assignId(clue.getId())
                            .userId(user.getUserId())
                            .userName(user.getUserName())
                            .deptId(user.getDeptId())
                            .createTime(new Date())
                            .createBy(user.getUserName())
                            .latest("1")
                            .type(String.valueOf(type))
                            .build())) {
                        throw new BaseException(ErrorMessageConstants.FAILED_TO_TRANSFER_CLUE);
                    }
                }
                map.put("flag", true);
                return map;
            case 1: // 商机
                // 获取用户还能持有的商机数
                LambdaQueryWrapper<TbAssignRecord> queryWrapper3 = new LambdaQueryWrapper<>();
                queryWrapper3.eq(TbAssignRecord::getType, type).eq(TbAssignRecord::getLatest, 1).eq(TbAssignRecord::getUserId, transferUserId);
                Integer businessCount = tbAssignRecordMapper.selectCount(queryWrapper3);
                LambdaQueryWrapper<TbRulePool> queryWrapper4 = new LambdaQueryWrapper<>();
                queryWrapper4.select(TbRulePool::getMaxNunmber);
                queryWrapper4.eq(TbRulePool::getType, type);
                Integer businessMax = tbRulePoolMapper.selectOne(queryWrapper4).getMaxNunmber();
                if (businessCount >= businessMax) {
                    throw new BaseException(ErrorMessageConstants.HOLDING_TOO_MANY_BUSINESS);
                }
                // 获取要转派的商机
                List<TbBusiness> businessList = tbBusinessMapper.getTransferBusinessListByUserId(userId);
                // 逐一转派
                for (int i = 0; i < businessList.size(); i++) {
                    if (businessCount++ >= businessMax) {
                        map.put("flag", false);
                        map.put("msg", "成功分配" + i + "个商机，剩余" + (businessList.size() - i) + "个商机分配失败");
                        return map;
                    }
                    TbBusiness business = businessList.get(i);
                    tbAssignRecordMapper.updateTbAssignRecordByAssignId(business.getId());
                    if (!save(TbAssignRecord.builder()
                            .assignId(business.getId())
                            .userId(user.getUserId())
                            .userName(user.getUserName())
                            .deptId(user.getDeptId())
                            .createTime(new Date())
                            .createBy(user.getUserName())
                            .latest("1")
                            .type(String.valueOf(type))
                            .build())) {
                        throw new BaseException(ErrorMessageConstants.FAILED_TO_TRANSFER_BUSINESS);
                    }
                }
                map.put("flag", true);
                return map;
            default:
                throw new BaseException(ErrorMessageConstants.TRANSFER_PARAMS_EXCEPTION);
        }
    }

}
